import { useEffect, useRef, useState } from 'react';

/**
 * 获取窗口可视化高度
 *
 * @returns {{width: number, height: number}}
 */
export default function useWindowSize() {
  const [height, setHeight] = useState(0);
  const [width, setWidth] = useState(0);

  const isMounted = useRef(null);

  useEffect(() => {
    isMounted.current = true;

    const handleResize = () => {
      if (isMounted.current) {
        setHeight(window.innerHeight);
        setWidth(window.innerWidth);
      }
    };

    window.addEventListener('resize', handleResize);
    handleResize();

    return () => {
      isMounted.current = false;
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return {
    width,
    height
  };
}
